// 2D 火柴人横版平台射击（纯原生 Canvas）
(function(){
  const canvas = document.getElementById('game');
  const ctx = canvas.getContext('2d');
  const hpEl = document.getElementById('hp');
  const killsEl = document.getElementById('kills');
  const statusEl = document.getElementById('status');
  const startScreen = document.getElementById('start-screen');
  const diffButtons = startScreen ? startScreen.querySelectorAll('[data-diff]') : [];
  diffButtons.forEach(btn => {
     btn.addEventListener('click', () => {
       const d = parseInt(btn.dataset.diff, 10) || 1;
       difficulty = d;
       gameStarted = true;
       if(startScreen) startScreen.style.display = 'none';
       statusEl.textContent = '';
       bullets.length = 0;
       player.x = 120; player.y = floorY - 120; player.vx=0; player.vy=0; player.hp=100; player.facing=1; player.crouch=false; player.hitCooldown=0; player.state='alive';
       spawnMonsters();
     });
   });

  // 画布与摄像机
  function resize(){ canvas.width = window.innerWidth; canvas.height = window.innerHeight; }
  window.addEventListener('resize', resize); resize();
  const camera = { x: 0, y: 0 };
  // 游戏状态与难度
  let gameStarted = false; // 点击难度后置为 true
  let difficulty = 1; // 1 | 2 | 3

  // 世界参数
  const world = { gravity: 1800, width: 2400, height: 1200 };// 像素单位
  const floorY = 1000; // 最底层 y（平台顶面）

  // 输入
  const keys = { w:false, a:false, s:false, d:false, j:false, r:false, t:false };
  const keymap = { KeyW:'w', KeyA:'a', KeyS:'s', KeyD:'d', KeyJ:'j', KeyR:'r', KeyT:'t' };
  let lastSDown = 0; // 双击S检测

  window.addEventListener('keydown', (e)=>{
    const k = keymap[e.code]; if(!k) return;
    keys[k] = true;
    if(k==='s'){
      const now = performance.now();
      if(now - lastSDown < 250){ requestDropThrough(); }
      lastSDown = now;
    }
  });
  window.addEventListener('keyup', (e)=>{ const k = keymap[e.code]; if(!k) return; keys[k] = false; });

  // 平台（多样化）: x, y(顶面), w, h, pass(true=可穿), id
  const platforms = [];
  let pid = 1;
  function addPlatform(x,y,w,h,pass){ platforms.push({ id: pid++, x, y, w, h, pass }); }

  // 生成场景：多个平台、底层不可穿
  function buildLevel(){
    platforms.length = 0;
    // 底层平台（不可穿）
    addPlatform(0, floorY, world.width, 40, false);
    // 其他平台（全部可走、允许下穿）
    addPlatform(150, 760, 300, 20, false);
    addPlatform(520, 680, 260, 20, false);
    addPlatform(900, 820, 400, 20, false);
    addPlatform(1320, 700, 320, 20, false);
    addPlatform(1680, 600, 280, 20, false);
    addPlatform(400, 520, 240, 20, false);
    addPlatform(1000, 480, 300, 20, false);
    addPlatform(1600, 420, 260, 20, false);
    addPlatform(400, 300, 200, 20, false);
    addPlatform(1200, 280, 220, 20, false);
    // 新增行走边框（提高数量）
    addPlatform(200, 900, 260, 20, false);
    addPlatform(720, 900, 220, 20, false);
    addPlatform(1160, 900, 240, 20, false);
    addPlatform(1560, 900, 220, 20, false);
    addPlatform(200, 640, 220, 20, false);
    addPlatform(820, 620, 220, 20, false);
    addPlatform(1240, 560, 260, 20, false);
    addPlatform(1840, 540, 200, 20, false);
    addPlatform(260, 380, 180, 20, false);
    addPlatform(800, 360, 200, 20, false);
    addPlatform(1360, 340, 220, 20, false);
  }
  buildLevel();

  // 实体基类
  class Body {
    constructor(x,y,w,h){ this.x=x; this.y=y; this.w=w; this.h=h; this.vx=0; this.vy=0; this.onGround=false; this.groundId=null; }
    get left(){ return this.x; } get right(){ return this.x + this.w; }
    get top(){ return this.y; } get bottom(){ return this.y + this.h; }
  }

  // 玩家（火柴人）
  class Player extends Body {
    constructor(){
      super(120, floorY-120, 40, 120);
      this.team = 'player';
      this.hp = 100;
      this.facing = 1;
      this.crouch = false;
      this.dropThroughUntil = 0;
      this.fireCooldown = 0;
      this.hitCooldown = 0; // 初始化受击冷却
      this.state = 'alive'; // alive | dying
      this.fireRate = 8;
      this.moveSpeed = 380; this.crouchSpeed = 220;
      this.jumpSpeed = 820;
      this.weapon = { name: 'M4A1', damage: 20 };
    }
  }

  // 子弹
  class Bullet {
    constructor(x,y,dir){ this.x=x; this.y=y; this.vx=dir*900; this.vy=0; this.w=18; this.h=4; this.damage=10; this.alive=true; this.life=0; this.team='player'; }
    get left(){ return this.x; }
    get right(){ return this.x + this.w; }
    get top(){ return this.y; }
    get bottom(){ return this.y + this.h; }
  }
  // 敌方（Boss）球状子弹
  class EnemyBullet {
    constructor(x,y,dx,dy){ const speed=700; const len=Math.hypot(dx,dy)||1; this.x=x; this.y=y; this.vx=dx/len*speed; this.vy=dy/len*speed; this.w=12; this.h=12; this.damage=50; this.alive=true; this.life=0; this.team='monster'; }
    get left(){ return this.x; }
    get right(){ return this.x + this.w; }
    get top(){ return this.y; }
    get bottom(){ return this.y + this.h; }
  }

  // 怪物
  const MONSTER_TYPES = {
     normal:{ hp:30, decorator:'none' },
     elite:{ hp:50, decorator:'horn' },
     boss:{ hp:100, decorator:'cowboy' },
   };
   // 怪物接触伤害表
   const MONSTER_CONTACT_DAMAGE = { normal:20, elite:30, boss:50 };
   class Monster extends Body {
     constructor(type, plat){
       const w=40, h=120;
       const x = Math.min(Math.max(plat.x+20,  plat.x + Math.random()*(plat.w-60)), plat.x+plat.w-60);
       const y = plat.y - h;
       super(x,y,w,h);
       this.team = 'monster';
       this.type = type; this.hp = MONSTER_TYPES[type].hp; this.decorator = MONSTER_TYPES[type].decorator;
       this.color = randomMonsterColor();
       this.facing = Math.random()<0.5?1:-1;
       this.speed = type==='boss'? 140 : (type==='elite'? 180 : 200);
       this.platformId = plat.id;
       this.alive = true;
       this.state = 'alive';
       this.deathTimer = 0;
       this.walkPhase = 0;
       this.hurtTimer = 0; // 受击短暂状态
       // 新增：全图追踪相关属性
       this.agro = false; // 被攻击或看到玩家后变为 true
       this.jumpSpeed = 780; // 追踪时用于跳跃
       this.dropThroughUntil = 0; // 追踪时用于临时下穿
     }
   }

  function randomMonsterColor(){
    // 随机亮色，避免与玩家黑色冲突
    const hues = [0,40,80,120,160,200,240,280,320];
    const h = hues[Math.floor(Math.random()*hues.length)];
    return `hsl(${h}deg 80% 60%)`;
  }

  const player = new Player();
  const bullets = [];
  const monsters = [];
  const particles = []; // 受击碎屑粒子
  let kills = 0;

  function spawnMonsters(){
    monsters.length = 0;
    const spawnPlats = platforms;
    // 计算平台层级（按 y 从小到大排序，越小越上层）
    const levelsAsc = Array.from(new Set(spawnPlats.map(p=>p.y))).sort((a,b)=>a-b);
    const top3Levels = levelsAsc.slice(0,3);
    const bossAllowedPlats = spawnPlats.filter(p => top3Levels.includes(p.y));
    // 难度计数
    let counts = { normal: 10, elite: 3, boss: 0 };
    if(difficulty===2) counts = { normal: 10, elite: 5, boss: 1 };
    if(difficulty===3) counts = { normal: 10, elite: 5, boss: 2 };
    // 生成普通与精英（任意平台）
    for(let i=0;i<counts.normal;i++){
      const plat = spawnPlats[Math.floor(Math.random()*spawnPlats.length)];
      monsters.push(new Monster('normal', plat));
    }
    for(let i=0;i<counts.elite;i++){
      const plat = spawnPlats[Math.floor(Math.random()*spawnPlats.length)];
      monsters.push(new Monster('elite', plat));
    }
    // Boss（难度二与难度三：只在上面三层）
     for(let i=0;i<counts.boss;i++){
       const pool = ((difficulty>=2) && bossAllowedPlats.length>0) ? bossAllowedPlats : spawnPlats;
       const plat = pool[Math.floor(Math.random()*pool.length)];
       monsters.push(new Monster('boss', plat));
     }
  }
  spawnMonsters();

  // 下落穿平台
  function requestDropThrough(){
    player.dropThroughUntil = performance.now() + 300;
    if(player.onGround){ player.onGround = false; }
  }
  function isDropping(){ return performance.now() < player.dropThroughUntil; }

  // 更新物理与行为
  function update(dt){
    // 未开始则暂停更新（等待选择难度）
    if(!gameStarted) return;
    // 玩家输入与移动
    const wasAlive = player.state === 'alive';
    if(wasAlive){
      player.crouch = keys.s;
      const maxSpeed = player.crouch ? player.crouchSpeed : player.moveSpeed;
      let desiredVX = 0;
      if(keys.a) { desiredVX -= maxSpeed; player.facing = -1; }
      if(keys.d) { desiredVX += maxSpeed; player.facing = 1; }
      // 允许空中左右移动（移除仅在平台上移动的限制）
      player.vx = desiredVX;
      if(keys.w && player.onGround){ player.vy = -player.jumpSpeed; player.onGround=false; player.groundId = null; }
    } else {
      // 死亡时禁用移动与跳跃
      player.crouch = false; player.vx = 0;
    }
    // 重力
    player.vy += world.gravity * dt;
    // 水平移动与边界
    player.x += player.vx * dt;
    player.x = Math.max(0, Math.min(world.width - player.w, player.x));
    // 垂直移动与平台碰撞（死亡状态下忽略全部平台，直接自由落体）
    player.y += player.vy * dt;
    player.onGround = false;
    if(player.state !== 'dying'){
      for(const p of platforms){
        const wasAbove = (player.y - player.vy*dt + player.h) <= p.y + 2;
        const dropping = isDropping() && player.groundId === p.id && p.y < floorY;
        if(dropping) { continue; }
        // 修正：仅在水平范围重叠的平台顶面才允许着陆，移除“虚无地面”
        const horizontallyOver = (player.right > p.x) && (player.left < p.x + p.w);
        if(horizontallyOver && wasAbove && player.vy >= 0 && player.bottom >= p.y){
          player.y = p.y - player.h; player.vy = 0; player.onGround = true; player.groundId = p.id;
        }
      }
    }
    // 蹲下碰撞箱高度
    if(player.crouch){ player.h = 80; } else { player.h = 120; }
    // 射击（仅存活）
    player.fireCooldown -= dt; player.hitCooldown -= dt;
    if(keys.j && player.fireCooldown <= 0 && player.state==='alive'){
      const bX = player.x + (player.facing>0 ? player.w : -18);
      const bY = player.y + player.h*0.45;
      const bullet = new Bullet(bX, bY, player.facing);
      bullets.push(bullet);
      player.fireCooldown = 1 / player.fireRate;
    }
  
    // 子弹更新与碰撞（命中后立即移除，不穿透）
    for(const b of bullets){
      b.life += dt;
      b.x += b.vx * dt;
      b.y += b.vy * dt;
      const offX = (b.x<-100 || b.x>world.width+100);
      const offY = (b.y<-100 || b.y>world.height+100);
      const maxLife = b.team==='monster'? 3 : 2;
      if(b.life>maxLife || offX || offY) b.alive=false;
    }
    for(const b of bullets){
      if(!b.alive) continue;
      for(const m of monsters){
        if(m.state!=='alive') continue;
        if(b.team==='player' && m.team==='monster' && rectOverlap(b,m)){
          m.hp -= b.damage; b.alive=false;
          // 受击表现
          m.hurtTimer = 0.25;
          // 新增：被攻击后进入全图追踪
          m.agro = true;
          const cx = m.x + m.w*0.5, cy = m.y + m.h*0.35;
          for(let i=0;i<10;i++){
            const ang = Math.random()*Math.PI*2;
            const spd = 200 + Math.random()*280;
            particles.push({ x: cx, y: cy, vx: Math.cos(ang)*spd, vy: Math.sin(ang)*spd - 80, life: 0, max: 0.5, color: m.color });
          }
          if(m.hp<=0){ m.state='dying'; m.deathTimer = 1.2; }
          break;
        }
      }
    }
    // 敌方子弹命中玩家（即刻扣血50）
    for(const b of bullets){
      if(!b.alive) continue;
      if(b.team==='monster' && player.state==='alive' && rectOverlap(b, player)){
        player.hp -= b.damage; b.alive=false;
        if(player.hp<=0){
          player.hp=0; player.state='dying'; player.onGround=false; player.groundId=null;
          statusEl.textContent='你已阵亡，按 R 重新开始'; gameOver=true;
        }
      }
    }
  
    // 怪物与玩家碰撞伤害（玩家死亡进入下落状态）
    for(const m of monsters){
      if(m.state!=='alive') continue;
      if(rectOverlap(player,m) && player.hitCooldown<=0 && player.state==='alive'){
        const contactDmg = MONSTER_CONTACT_DAMAGE[m.type] || 20;
        player.hp -= contactDmg; player.hitCooldown = 0.6;
        if(player.hp<=0){
          player.hp=0; player.state='dying'; player.onGround=false; player.groundId=null;
          statusEl.textContent='你已阵亡，按 R 重新开始'; gameOver=true;
        }
      }
    }
  
    // 怪物巡逻或死亡动画（受击计时衰减）
    for(const m of monsters){
      if(m.state==='alive'){
        // 删除原先在循环开头对 m.platformId 的强制存在校验，不再继续依赖原平台
        const mCenter = m.x + m.w*0.5;
        const pCenter = player.x + player.w*0.5;
        const seesPlayer = (Math.abs(pCenter - mCenter) < 1400) && (Math.abs((player.y + player.h*0.5) - (m.y + m.h*0.5)) < 100);
        const aggro = m.agro || seesPlayer;
        if(aggro){
          // 全图追踪：与玩家类似的跳跃与下穿
           m.facing = pCenter > mCenter ? 1 : -1;
           m.vx = m.facing * m.speed * 1.35;
           const playerAbove = (player.y + player.h*0.5) < (m.y + m.h*0.3);
           const playerBelow = (player.y + player.h*0.5) > (m.y + m.h*0.7);
           // 跳跃（玩家在上方且怪物着地）
           if(m.onGround && playerAbove){
             m.vy = -m.jumpSpeed; m.onGround=false; m.groundId=null;
           }
           // 下穿（玩家在下方且怪物着地，且非底层）
           if(m.onGround && playerBelow && m.groundId){
             const gPlat = platforms.find(p=>p.id===m.groundId);
             if(gPlat && gPlat.y < floorY){
               m.dropThroughUntil = performance.now() + 300;
               m.onGround = false;
             }
           }
           // 重力与移动（与玩家一致）
           m.vy += world.gravity * dt;
           m.x += m.vx * dt; m.x = Math.max(0, Math.min(world.width - m.w, m.x));
           m.y += m.vy * dt;
           // 平台碰撞（与玩家相似）
           m.onGround = false;
           for(const p of platforms){
             const wasAbove = (m.y - m.vy*dt + m.h) <= p.y + 2;
             const dropping = (performance.now() < (m.dropThroughUntil||0)) && m.groundId === p.id && p.y < floorY;
             if(dropping) { continue; }
             const horizontallyOver = (m.right > p.x) && (m.left < p.x + p.w);
             if(horizontallyOver && wasAbove && m.vy >= 0 && m.bottom >= p.y){
               m.y = p.y - m.h; m.vy = 0; m.onGround = true; m.groundId = p.id; m.platformId = p.id;
             }
           }
           // Boss 发射球状子弹（保持原逻辑）
           m.shootCooldown = (m.shootCooldown ?? 0) - dt;
           if(m.type==='boss' && m.shootCooldown<=0){
             const sx = m.x + m.w*0.5; const sy = m.y + m.h*0.35;
             const px = player.x + player.w*0.5; const py = player.y + player.h*0.5;
             const eb = new EnemyBullet(sx, sy, px - sx, py - sy);
             bullets.push(eb);
             m.shootCooldown = 1.2;
           }
         } else {
           // 原平台内巡逻：仅当不追踪时才限制在平台内
           const plat = platforms.find(p=>p.id===m.platformId); if(!plat) continue;
           m.vx = m.facing * m.speed; m.x += m.vx * dt;
           if(m.x < plat.x){ m.x = plat.x; m.facing = 1; }
           if(m.x + m.w > plat.x + plat.w){ m.x = plat.x + plat.w - m.w; m.facing = -1; }
         }
        m.walkPhase += Math.abs(m.vx) * dt * 0.02;
        m.hurtTimer = Math.max(0, m.hurtTimer - dt);
      } else if(m.state==='dying'){
        m.deathTimer -= dt; m.vy += world.gravity * dt; m.y += m.vy * dt;
        if(m.deathTimer<=0) { m.state='dead'; m.alive=false; }
      }
    }
  
    // 清理死亡子弹
    for(let i=bullets.length-1;i>=0;i--) if(!bullets[i].alive) bullets.splice(i,1);
  
    // HUD 与摄像机
    hpEl.textContent = Math.max(0, Math.floor(player.hp));
    killsEl.textContent = monsters.filter(m=>m.state==='dead').length;
    // 视角跟随（水平+垂直，带平滑）
    const targetX = Math.max(0, Math.min(world.width - canvas.width, player.x - canvas.width*0.35));
    const playerCenterY = player.y + player.h*0.5;
    let targetY = playerCenterY - canvas.height*0.5; // 将玩家置于视口中间
    targetY = Math.max(0, Math.min(Math.max(0, world.height - canvas.height), targetY));
    const smooth = 10; // 越大越紧跟
    const alpha = Math.min(1, smooth * dt);
    camera.x += (targetX - camera.x) * alpha;
    camera.y += (targetY - camera.y) * alpha;
  
    // 全部怪物死亡则提示重开
     if(monsters.every(m=>m.state==='dead')){ statusEl.textContent = '所有怪物已被消灭，按 R 返回开始界面'; }
     // 返回开始界面重新选择难度
     if(keys.r){
       gameStarted = false;
       if(startScreen) startScreen.style.display = '';
       statusEl.textContent = '请选择难度开始游戏';
     }
     // 重置当前难度关卡
     if(keys.t){ restart(); }
  }

  // 简单矩形碰撞
  function rectOverlap(a,b){ return a.right > b.x && a.left < b.x + b.w && a.bottom > b.y && a.top < b.y + b.h; }

  // 绘制
  function draw(){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    // 背景与平台
    ctx.fillStyle = '#0f172a'; ctx.fillRect(0,0,canvas.width,canvas.height);
    for(const p of platforms){ const x = p.x - camera.x, y = p.y - camera.y; ctx.fillStyle = '#111827'; ctx.fillRect(x, y, p.w, p.h); ctx.strokeStyle = '#ffffff'; ctx.strokeRect(x, y, p.w, p.h); }
  
    // 玩家
    drawStickman(player, '#ffffff', undefined, player.state);
    drawWeapon(player);
  
    // 子弹（玩家：矩形；Boss：红色圆形）
    for(const b of bullets){
      const bx = b.x - camera.x, by = b.y - camera.y;
      if(b.team==='player'){
        ctx.fillStyle = '#f59e0b';
        ctx.fillRect(bx, by, b.w, b.h);
      } else {
        ctx.fillStyle = '#ef4444';
        ctx.beginPath(); ctx.arc(bx + b.w/2, by + b.h/2, Math.max(6, Math.min(b.w,b.h)/2), 0, Math.PI*2); ctx.fill();
      }
    }
  
    // 怪物与血条
    for(const m of monsters){ if(m.state==='dead') continue; drawStickman(m, m.color, m.decorator, m.state); drawHPBar(m); }
  }

  function drawStickman(body, color, deco, state){
    const x = body.x - camera.x, y = body.y - camera.y;
    const w = body.w, h = body.h;
    ctx.strokeStyle = color; ctx.lineWidth = 6; ctx.lineCap = 'round';
    const headR = Math.min(18, h*0.18);
    const headX = x + w*0.5; const headY = y + headR + 4;
    const torsoTop = headY + headR; const torsoBottom = y + h*0.75;
    if(state==='dying'){ ctx.save(); ctx.translate(headX, torsoBottom); ctx.rotate(Math.PI/6); ctx.translate(-headX, -torsoBottom); }
    // 头
    ctx.beginPath(); ctx.arc(headX, headY, headR, 0, Math.PI*2); ctx.stroke();
    // 眼睛（怪物红眼）
    if(body.team==='monster'){
      ctx.fillStyle = '#ef4444';
      const eOff = headR*0.35; const eY = headY - headR*0.2;
      ctx.beginPath(); ctx.arc(headX - eOff, eY, 2.5, 0, Math.PI*2); ctx.fill();
      ctx.beginPath(); ctx.arc(headX + eOff, eY, 2.5, 0, Math.PI*2); ctx.fill();
    }
    // 装饰（保留现有）
    if(deco==='horn'){ ctx.fillStyle = color; ctx.beginPath(); ctx.moveTo(headX - headR*0.8, headY - headR*0.9); ctx.lineTo(headX - headR*1.3, headY - headR*1.6); ctx.lineTo(headX - headR*0.4, headY - headR*1.0); ctx.closePath(); ctx.fill(); ctx.beginPath(); ctx.moveTo(headX + headR*0.8, headY - headR*0.9); ctx.lineTo(headX + headR*1.3, headY - headR*1.6); ctx.lineTo(headX + headR*0.4, headY - headR*1.0); ctx.closePath(); ctx.fill(); }
    if(deco==='spike'){ ctx.fillStyle = color; for(let i=-3;i<=3;i++){ const bx = headX + i*headR*0.5; const by = headY - headR*1.2; ctx.beginPath(); ctx.moveTo(bx, by); ctx.lineTo(bx + headR*0.25, by - headR*0.9); ctx.lineTo(bx + headR*0.5, by); ctx.closePath(); ctx.fill(); } }
    if(deco==='cowboy'){ ctx.fillStyle = color; const brimY = headY - headR*0.6; ctx.fillRect(headX - headR*1.2, brimY, headR*2.4, headR*0.2); ctx.beginPath(); ctx.moveTo(headX - headR*0.6, brimY); ctx.lineTo(headX - headR*0.4, brimY - headR*0.7); ctx.lineTo(headX + headR*0.4, brimY - headR*0.7); ctx.lineTo(headX + headR*0.6, brimY); ctx.closePath(); ctx.fill(); }
    // 身体
    ctx.beginPath(); ctx.moveTo(headX, torsoTop); ctx.lineTo(headX, torsoBottom); ctx.stroke();
    // 手臂：怪物下垂摆动；玩家保持水平持枪
    const speed = Math.abs(body.vx || 0);
    if(body.team==='monster'){
      const baseX = headX; const armTop = torsoTop + (torsoBottom-torsoTop)*0.25;
      const swing = Math.sin(body.walkPhase||0) * (speed>1? h*0.10 : h*0.02);
      // 左臂
      ctx.beginPath(); ctx.moveTo(baseX, armTop);
      ctx.lineTo(baseX - w*0.35, armTop + h*0.35 + swing);
      ctx.lineTo(baseX - w*0.15, armTop + h*0.60);
      ctx.stroke();
      // 右臂
      ctx.beginPath(); ctx.moveTo(baseX, armTop);
      ctx.lineTo(baseX + w*0.35, armTop + h*0.35 - swing);
      ctx.lineTo(baseX + w*0.15, armTop + h*0.60);
      ctx.stroke();
    } else {
      const armDir = body.facing>0?1:-1; const armY = torsoTop + (torsoBottom-torsoTop)*0.35; const armLen = w*0.9;
      ctx.beginPath(); ctx.moveTo(headX, armY); ctx.lineTo(headX + armDir*armLen*0.9, armY); ctx.stroke();
      ctx.beginPath(); ctx.moveTo(headX, armY+8); ctx.lineTo(headX + armDir*armLen*0.8, armY+8); ctx.stroke();
    }
    // 腿部动画恢复为原来的简化摆动（玩家与怪物一致）
     body.walkPhase = (body.walkPhase || 0) + speed * 0.0008;
     const legSwing = Math.sin(body.walkPhase) * (speed>1? h*0.08 : 0);
     const kneeOffset = h*0.12; const baseX = headX; const baseY = torsoBottom;
     ctx.beginPath(); ctx.moveTo(baseX, baseY); ctx.lineTo(baseX - w*0.35, baseY + kneeOffset + legSwing); ctx.lineTo(baseX - w*0.15, baseY + kneeOffset*2); ctx.stroke();
     ctx.beginPath(); ctx.moveTo(baseX, baseY); ctx.lineTo(baseX + w*0.35, baseY + kneeOffset - legSwing); ctx.lineTo(baseX + w*0.15, baseY + kneeOffset*2); ctx.stroke();
     if(state==='dying'){ ctx.restore(); }
  }
  // 显示怪物血量条（在闭包内，访问 camera/MONSTER_TYPES）
  function drawHPBar(m){
    const x = m.x - camera.x, y = m.y - camera.y - 12;
    const w = m.w; const h = 6;
    ctx.fillStyle = 'rgba(0,0,0,0.5)'; ctx.fillRect(x, y, w, h);
    const ratio = Math.max(0, Math.min(1, m.hp / MONSTER_TYPES[m.type].hp));
    ctx.fillStyle = '#facc15'; // 黄色血条
    ctx.fillRect(x, y, w * ratio, h);
    ctx.strokeStyle = 'rgba(255,255,255,0.2)'; ctx.strokeRect(x, y, w, h);
  }
  // 重开游戏
  function restart(){
    player.x = 120; player.y = floorY - 120; player.vx=0; player.vy=0; player.hp=100; player.facing=1; player.crouch=false; player.hitCooldown=0; player.state='alive'; gameOver=false;
    bullets.length = 0;
    spawnMonsters(); // 按当前难度重新生成
    statusEl.textContent = '';
  }

  function drawWeapon(p){
    const x = p.x - camera.x, y = p.y - camera.y; const facing = p.facing;
    const gunLen = 64; const gunH = 12; const baseX = x + p.w*0.5; const armY = y + p.h*0.45;
    ctx.fillStyle = '#222'; ctx.strokeStyle = '#555'; ctx.lineWidth = 2;
    const gx = baseX + (facing>0? 8 : -gunLen-8);
    ctx.fillRect(gx, armY - gunH/2, gunLen, gunH);
    ctx.fillStyle = '#2f2f2f'; const barrel = facing>0? {x: gx+gunLen, w: 18} : {x: gx-18, w: 18};
    ctx.fillRect(barrel.x, armY - 3, facing>0? barrel.w : -barrel.w, 6);
  }

  // 主循环
  let last = performance.now();
  function loop(now){ const dt = Math.min(0.033, (now-last)/1000); last = now; update(dt); draw(); requestAnimationFrame(loop); }
  requestAnimationFrame(loop);
})();

// 开始新游戏：根据难度重置玩家与状态并生成怪物

// 返回开始界面：暂停更新并显示难度选择